package org.example.leetCode;

/**
 * @Author Qinkai
 * @Description TODO $
 * @Date $ 2021-09-22$
 * @Param $
 * @return $
 **/
public class SplitListToParts {
    public static void main(String[] args) {
        SplitListToParts splitListToParts = new SplitListToParts();
        ListNode l1 = new ListNode();
        ListNode l2 = new ListNode();
        ListNode l3 = new ListNode();
        l1.val = 1;
        l2.val = 2;
        l3.val = 3;

        l1.next = l2;
        l2.next = l3;

        ListNode[] listNodes = splitListToParts.splitListToParts(l1, 2);
        System.out.println(listNodes);
    }


    public ListNode[] splitListToParts(ListNode head, int k) {
        int size = 0;
        ListNode temp = head;
        while (temp != null) {
            temp = temp.next;
            size++;
        }

        int count = size / k;
        int z = size % k;
        ListNode[] listNodes = new ListNode[k];
        temp = head;
        for (int i = 0; i < k && temp != null; i++) {
            listNodes[i] = temp;
            int cursize = count + (z-- > 0 ? 1 : 0);
            for (int j = 0; j < cursize - 1; j++) {
                temp = temp.next;
            }

            ListNode next = temp.next;
            temp.next = null;
            temp = next;

        }
        return listNodes;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
